var Poker = require('../Poker/Poker');
var NN = require('../Poker/NN');

var PokerPlayer = require('../Poker/player').PokerPlayer;

var Const = require('./const');

exports.HLNNPlayer = PokerPlayer.extend({
    _robDealer: -1,            // 抢庄状态，-1/0/1 未选择/不抢/抢庄
    _selectedCards: null,     // 选择的三张牌
    _ante: 0,
    _playCards: false,
    _calcCards: null,
    _lookCards: false,
    _giveUp: false,
    _roundResult: null,

    init: function(uid, msg) {
        this._super(uid, msg);

        this._robDealer = -1;
        this._selectedCards = null;
        this._ante = 0;
        this._playCards = false;
        this._stat.roundPattern = Const.Pattern.NONE;
        this._calcCards = [];
        this._lookCards = false;
        this._giveUp = false;
        this._roundResult = {};
    },

    setRotDealer: function(value) {
        this._robDealer = value;
    },

    getRobDealer: function() {
        return this._robDealer;
    },

    setAnte: function(value) {
        this._ante = value;

        var room = this.getRoom();
        room.broadcast("onPlayerAnteChange", {
            playerIndex: this.getIndex(),
            ante: this._ante
        });
    },

    getAnte: function() {
        return this._ante;
    },

    setRoundPattern: function(pattern, score) {
        this._stat.roundPattern = pattern;
        this._stat.roundPatternScore = score || 0;

        this.setRoundResult(pattern);
    },

    setRoundResult: function (pattern) {

        if (pattern == Const.Pattern.wuNiu) {
            return;
        }

        if (this._roundResult[pattern]) {
            this._roundResult[pattern] += 1;
        }else {
            this._roundResult[pattern] = 1;
        }
    },

    getRoundPattern: function() {
        return this._stat.roundPattern;
    },

    getRoundPatternScore : function () {
        return this._stat.roundPatternScore;
    },

    setSelectedCards: function(cardsArr) {
        if (!cardsArr || cardsArr.length == 0) {
            this._selectedCards = [];
            return true;
        }

        var cards = Poker.buildFromArray(cardsArr);
        var allExist = true;
        var allPoint = 0;

        ExObject.eachKeyNum(cards, function(card, num) {
            if (!card) {
                allExist = false;
            }

            if (this._handCards.getCardNum(card) < num) {
                allExist = false;
            }

            allPoint += NN.getPoint(card) * num;
        }.bind(this));

        if (!allExist) {
            return false;
        }

        if (allPoint % NN.BASE != 0) {
            return false;
        }

        this._selectedCards = [];
        cardsArr.forEach(function(card) {
            this._selectedCards.push(card);
        }.bind(this));

        return true;
    },

    isSelectedCards: function() {
        return (this._selectedCards) ? true : false;
    },

    getSelectedCards : function () {
        return this._selectedCards;
    },

    ///**
    // * 获取返回的手牌组
    // * @returns {Array}
    // */
    //getArrCard : function () {
    //
    //    var handcards = clone (this._handCards.getCards());
    //    var returnHand = [];
    //
    //    ExObject.each(handcards, function (k, v) {
    //
    //        if (k) {
    //            returnHand.push (k);
    //        }
    //    });
    //
    //    return returnHand;
    //},

    /******************************************************************
     * 重载的接口
     ******************************************************************/

    getInfo: function() {
        var info = this._super();
        info.remainScore = this._stat.remainScore;
        return info;
    },

    getReconnectInfo: function(isSelf) {
        var info = this._super(isSelf);

        info.robDealer = this._robDealer;
        info.ante = this._ante;
        info.score = this.getScore();

        if (isSelf) {
            info.initCards = this.getHandCards().getInitCards();
        }

        if (isSelf || this._playCards) {
            info.handCards = this.getHandCards().getInitCards();
            info.selectCards = this._selectedCards;
            info.roundPattern = this.getRoundPattern();
            info.length = this.getHandCards().getCardNum();
        }

        info.playCards = this._playCards;
        return info;
    },

    getInitHandCardNeedNum: function() {
        var room = this.getRoom();
        if (room.getOption("threeCardNiu")) {
            return 3;
        }else {
            return 5;
        }
    },

    //getInitHandCardPreCards: function() {
    //    var preCards = [];
    //    if(this.getIndex() == 1){
    //        preCards.push(105);
    //        preCards.push(205);
    //        preCards.push(305);
    //    }else if(this.getIndex() == 2){
    //        preCards.push(210);
    //        preCards.push(310);
    //        preCards.push(110);
    //    }
    //    return preCards;
    //},

    getSettlementInfo: function() {
        var info = this._super();

        info.handCards = this.getHandCards().getInitCards();
        info.selectCards = this._selectedCards;
        info.roundResult = this._roundResult;

        return info;
    },

    /**
     * 检查当前是否是炸弹牛
     * @returns {boolean}
     */
    checkBoomNiu : function () {

        // 获取手牌中的张数
        var handCards = this._handCards.getCards();
        var isBoom = false;
        var length = this._handCards.getCardNum();

        ExObject.each (handCards, function (k, v) {

            if (k && v == 4 && length == 5) {
                this._calcCards = k;
                isBoom = true;
            }else if (k && length == 3 && v == 3) {
                this._calcCards = k;
                isBoom = true;
            }
        });

        return isBoom;
    },

    /**
     * 获取总的牌的值
     * @returns {number}
     */
    getSumCard : function () {

        var sum = 0;
        var handCards = this.getHandCards().getInitCards();

        for (var index = 0; index < handCards.length; ++index) {
            sum += NN.getPoint(handCards[index]);
        }

        return sum;
    },

    /**
     * 检测五张牌里面的牛牌组
     * @returns {{}}
     */
    checkFiveNiu : function () {

        var niuScore;
        var len = 5;
        var cardsArr = this.getHandCards().getInitCards ();
        for (var c1 = 0; c1 < len - 2; ++c1) {
            for (var c2 = c1 + 1; c2 < len - 1; ++c2) {
                for (var c3 = c2 + 1; c3 < len; ++c3) {
                    var point = NN.getPoint(cardsArr[c1]) + NN.getPoint(cardsArr[c2]) + NN.getPoint(cardsArr[c3]);
                    if (point % NN.BASE == 0) {
                        niuScore = point;

                        this._selectedCards = [cardsArr[c1], cardsArr[c2], cardsArr[c3]];

                        return niuScore;
                    }
                }
            }
        }

        return niuScore;
    },

    checkThreeNiu : function () {

        var niuScore;
        var len = 3;
        var cardsArr = this.getHandCards().getInitCards();
        for (var c1 = 0; c1 < len - 1; ++c1) {
            for (var c2 = c1 + 1; c2 < len; ++c2) {
                var point = NN.getPoint(cardsArr[c1]) + NN.getPoint(cardsArr[c2]);
                if (point % NN.BASE == 0) {
                    niuScore = point;

                    this._selectedCards = [cardsArr[c1], cardsArr[c2]];

                    return niuScore;
                }
            }
        }

        return niuScore;
    },

    /**
     * 对选入的牌进行判断牛分数
     * @param cards
     * @returns {*}
     */
    checkSelected : function (cards) {
        var niuScore;

        var point = 0;
        for (var index = 0; index < cards.length; ++index) {
            point += NN.getPoint(cards[index])
        }

        if (point % NN.BASE == 0) {
            niuScore = point;
        }

        this._selectedCards = cards;

        return niuScore;
    },

    getColorNum : function () {

        var handCards = this.getHandCards().getInitCards();
        var colorNum = 0;

        for (var index = 0 ; index < handCards.length; ++index) {
            if (Poker.getPoint(handCards[index]) > 10) {
                colorNum += 1;
            }
        }

        return colorNum;
    },

    getTenNum : function () {

        var handCards = this.getHandCards().getInitCards();
        var tenNum = 0;

        for (var index = 0 ; index < handCards.length; ++index) {
            if (Poker.getPoint(handCards[index]) == 10) {
                tenNum += 1;
            }
        }

        return tenNum;
    },

    /**
     * 结算牛牌型
     * @param niuScore  牛分数
     * @param length    手牌长度
     */
    settlementPattern : function (niuScore, length) {

        // 目前暂时用于分开判断
        var pattern;

        // 检测炸弹牛
        if (!this.getRoom().getOption("youNiuFan") &&
            this.checkBoomNiu ()) {
            pattern = Const.Pattern.boomNiu;
            this.setRoundPattern(pattern, Const.PatternScore[pattern]);
            return;
        }

        // 获取当前所有牌值的总和
        var sumValue = this.getSumCard ();

        // 检测五小牛
        if (!this.getRoom().getOption("youNiuFan") &&
            length == 5 &&
            sumValue <= Const.defaultConst.wuXiaoNiuValue) {
            pattern = Const.Pattern.wuXiaoNiu;
            this.setRoundPattern(pattern, Const.PatternScore[pattern]);
            return;
        }

        if (!niuScore) {
            pattern = Const.Pattern.wuNiu;
            this.setRoundPattern(pattern, Const.PatternScore[pattern]);
            return;
        }

        // 获取当前牌中的花牌张数
        var colorNum = this.getColorNum();

        // 获取当前牌中的10的张数
        var tenNum = this.getTenNum();

        // 检测金牛
        if (colorNum == length) {
            pattern = Const.Pattern.jinNiu;
            this.setRoundPattern(pattern, Const.PatternScore[pattern]);
            return;
        }

        // 检测银牛
        if (colorNum == length - 1 && tenNum == 1) {
            pattern = Const.Pattern.yinNiu;
            this.setRoundPattern(pattern, Const.PatternScore[pattern]);
            return;
        }

        // 检测牛牛
        if (sumValue % 10 == 0) {
            pattern = Const.Pattern.niuniu;
            this.setRoundPattern(pattern, Const.PatternScore[pattern]);
            return;
        }

        // 最后是判断牛几
        var value = (sumValue - niuScore) % 10;

        pattern = Const.Pattern.wuNiu + value;
        this.setRoundPattern(pattern, Const.PatternScore[pattern]);
    },

    /**
     *
     * @param cards
     */
    checkPattern : function (cards) {

        // 获取当前的手牌数进行对应的牌型判断
        var length = this._handCards.getCardNum();

        var niuScore;
        // 检测牛牌型
        if (cards) {
            niuScore = this.checkSelected(cards);
        }else if (length == 5) {
            niuScore = this.checkFiveNiu ();
        }else if (length == 3) {
            niuScore = this.checkThreeNiu ();
        }else {
            console.log ("当前手牌数量有误，无法判断");
            return;
        }

        this.settlementPattern(niuScore, length);
    },

    onCurRoundFinished: function () {
        this._super();

        this._handCards.reset();

        this._robDealer = -1;
        this._selectedCards = null;
        this._ante = 0;
        this._playCards = false;
        this._stat.roundPattern = Const.Pattern.NONE;
        this._stat.roundPatternScore = Const.Pattern.NONE;
        this._calcCards = [];
        this._lookCards = false;
        this._giveUp = false;
    },

    /******************************************************************
     * 私有功能函数
     ******************************************************************/

    /**
     * 发送并且初始化当前玩家的手牌
     * @param cardArr
     */
    InitHandCards: function (cardArr) {
        this._handCards.init(cardArr);

        var cards = this.getHandCards().getInitCards();

        var length = 5;
        // 显示牌的长度
        if (this.getRoom().getOption("threeCardNiu")) {
            length = 3;
        }

        this.send ("onPlayerCard", {
           playerIndex : this.getIndex(),
            cardLength : length,
                 cards : cards
        });
    },

    _getMaxCard: function(cards) {
        var maxCard = 0;
        var allCardsArr = this.getHandCards().getInitCards();
        if(cards){
            allCardsArr = cards;
        }

        allCardsArr.forEach(function(card) {
            if (!maxCard || NN.cardLT(card, maxCard)) {
                maxCard = card;
            }
        });

        return maxCard;
    },

    compareEach: function(dealerPlayer){

        var player = this;

        // 之后可能有特殊情况的判断
        if (player._stat.roundPattern > dealerPlayer._stat.roundPattern) {
            return true;
        } else if (player._stat.roundPattern == dealerPlayer._stat.roundPattern) {
            var maxCard = 0;
            var playerMaxCard = 0;

            if (player._stat.roundPattern == Const.Pattern.boomNiu) {
                maxCard = dealerPlayer._getMaxCard(dealerPlayer._calcCards);
                playerMaxCard = player._getMaxCard(dealerPlayer._calcCards);
            } else {
                maxCard = dealerPlayer._getMaxCard();
                playerMaxCard = player._getMaxCard();
            }

            console.log("%d cccccc %d  index = %d", playerMaxCard, maxCard, dealerPlayer.getIndex());
            if (NN.cardLT(playerMaxCard, maxCard)) {
                return true;
            }
        }
        return false;
    }
});